package com.wf.smartcomm.server.serviceImpl;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wf.smartcomm.server.bean.Discount;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.model.Page;
import com.wf.smartcomm.server.service.DiscountService;
import com.wf.smartcomm.server.util.IdUtils;

@Service
@Transactional
public class DiscountServiceImpl implements DiscountService {
	@Resource
	private SessionFactory factory;
	
	@Override
	public void add(Discount fee) {
		fee.setObjectId(IdUtils.uuid());
		fee.setCreatedAt(String.valueOf(System.currentTimeMillis()));
		factory.getCurrentSession().persist(fee);
	}

	@Override
	public void delete(String... ids) {
		for (String id : ids) {
			factory.getCurrentSession().delete(factory.getCurrentSession().load(Discount.class, id));
		}
	}

	@Override
	public void update(Discount fee) {
		fee.setCreatedAt(String.valueOf(System.currentTimeMillis()));
		factory.getCurrentSession().merge(fee);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Discount get(String objectId) {
		return (Discount) factory.getCurrentSession().get(Discount.class, objectId);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public void list(Page page) {
		Query query = factory.getCurrentSession().createSQLQuery("select count(*) from Discount");
		Long counts = (Long) query.uniqueResult();
		page.setTotalCount(counts.intValue());
		query = factory.getCurrentSession().createQuery("from Discount order by createdAt");
		query.setMaxResults(page.getPageSize());
		query.setFirstResult(page.getBeginIndex());
		page.setDataList(query.list());
	}

	@Override
	public Discount get(Village village) {
		Query query = factory.getCurrentSession().createQuery("from Discount where village =:village order by createdAt desc limit 1");
		query.setParameter("village", village);
		//query.setMaxResults(1);
		return (Discount) query.uniqueResult();
	}

}
